from django import forms
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator  # 正则校验
import re
import hashlib
from app01 import models
import redis


class RegisterModelForm(forms.ModelForm):
    email = forms.CharField(
        label='邮箱',
        widget=forms.TextInput(
            attrs={
                'placeholder': '请输入邮箱'
            }
        ),
        error_messages={
            'required': '邮箱不能为空,请重新输入',
        }
    )

    mobile_phone = forms.CharField(
        label='手机号',
        widget=forms.TextInput(
            attrs={
                'placeholder': '请输入手机号',
                'id': 'mobile_phone'
            }
        ),
        validators=[RegexValidator(r'^(1[3-9])\d{9}$', '手机号格式错误，请重新输入'), ],
        error_messages={
            'required': '手机号不能为空,请重新输入',
        }
    )

    username = forms.CharField(
        label='用户名',
        widget=forms.TextInput(
            attrs={
                'placeholder': '请输入用户名'
            }
        ),
        min_length=6,
        error_messages={
            'required': '用户名不能为空,请重新输入',
            'min_length': '用户名最少6位,请重新输入',
            'unique': '用户名已存在,请重新输入'
        }
    )
    password = forms.CharField(
        label='密码',
        widget=forms.PasswordInput(
            attrs={
                'placeholder': '请输入密码',
            }
        ),
        min_length=6,
        error_messages={
            'required': '密码不能为空,请重新输入',
            'min_length': '密码最少6位,请重新输入'
        }
    )
    confirm_password = forms.CharField(
        label='确认密码',
        widget=forms.PasswordInput(
            attrs={
                'placeholder': '请输入确认密码'
            }
        ),
        min_length=6,
        error_messages={
            'required': '确认密码不能为空,请重新输入',
            'min_length': '确认密码最少6位,请重新输入'
        }
    )

    code = forms.CharField(
        label='验证码',
        widget=forms.TextInput(
            attrs={
                'placeholder': '请输入验证码'
            }
        ),
        min_length=6,
        error_messages={
            'required': '验证码不能为空,请重新输入',
            'min_length': '验证码最少6位,请重新输入'
        }
    )

    class Meta:
        model = models.UserInfo
        fields = ['username', 'email', 'password', 'confirm_password', 'mobile_phone', 'code']

    def clean_email(self):
        # 不符合校验规则 抛出异常
        # print(self.cleaned_data)
        value = self.cleaned_data.get('email')
        if not re.search(r'^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$', value):
            raise ValidationError('邮箱格式错误，请重新输入')
        # 符合校验规则 返回该字段的值
        return value

    def clean_code(self):
        # 不符合校验规则 抛出异常
        print(self.cleaned_data)
        code = self.cleaned_data.get('code')

        conn = redis.Redis(host='127.0.0.1', port=6379, password='foobared', encoding='utf-8')
        value = conn.get(self.cleaned_data['mobile_phone'])

        if int(code) != int(value):
            raise ValidationError('验证码错误，请重新输入')
        # 符合校验规则 返回该字段的值
        return value

    def clean(self):
        self._validate_unique = True
        password = self.cleaned_data.get('password')
        confirm_password = self.cleaned_data.get('confirm_password')
        if confirm_password != password:
            # 将错误信息加入到某个字段中
            self.add_error('confirm_password', '两次密码不一致,请重新输入')
            raise ValidationError('两次密码输入不一致')
        if password:
            self.cleaned_data['password'] = hashlib.md5(password.encode()).hexdigest()
        return self.cleaned_data

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            # field.widget.attrs['placeholder'] = f'请输入{field.label}'
